<?php

namespace App\Models\MLM;

use App\Models\BaseModel;
use Illuminate\Support\Facades\Log;

class MLMBalanceLog extends BaseModel
{

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $guarded = [];

    /**
     * The attributes excluded from the model's JSON form.
     *
     * @var array
     */
    protected $hidden = [
        'updated_at',
    ];

    protected $table = 'mlm_balance_log';
    protected $dateFormat = 'U';

    /**
     * 关联用户
     * @return \Illuminate\Database\Eloquent\Relations\HasOne
     */
    public function from(){
        return $this->hasOne('App\Models\User\User', 'user_id', 'from_id');
    }

    /**
     * add
     * @param $from_id
     * @param $to_id
     * @param $balance
     * @param $type
     */
    public function add($from_id, $to_id, $balance, $type)
    {
        $MLMBalance = new MLMBalanceLog();
        $MLMBalance->from_id = $from_id;
        $MLMBalance->to_id = $to_id;
        $MLMBalance->balance = $balance;
        $MLMBalance->type = $type;
        $MLMBalance->save();
    }

    /**
     * logs
     * @param $user_id
     * @param $page
     * @param $size
     * @return mixed
     */
    public function logs($user_id, $page, $size){
        $data = [];
        $data['list'] = $this->where('to_id', $user_id)
            ->withOnly('from', ['user_id', 'nickname', 'cover'])
            ->forPage($page, $size+1)
            ->orderBy('created_at', 'desc')
            ->get()
            ->toArray();
        $data['next_page'] = $page + 1;
        $data['page_size'] = $size;
        return $this->after($data);
    }
}
